<?php
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

require_once '../../includes/config.php';
require_once '../../includes/auth.php';

// 验证登录
$admin = verifyAdminToken();
if (!$admin) {
    http_response_code(401);
    echo json_encode(['code' => 401, 'message' => '未登录或登录已过期']);
    exit;
}

$action = $_GET['action'] ?? '';

switch ($action) {
    case 'list':
        getReservations();
        break;
    case 'detail':
        getReservationDetail();
        break;
    case 'review':
        reviewReservation();
        break;
    case 'export':
        exportReservations();
        break;
    default:
        http_response_code(400);
        echo json_encode(['code' => 400, 'message' => '无效的操作']);
        break;
}

function getReservations() {
    try {
        $date = $_GET['date'] ?? '';
        $status = $_GET['status'] ?? '';
        $type = $_GET['type'] ?? '';
        $keyword = $_GET['keyword'] ?? '';
        
        $reservations = [];
        $statistics = ['total' => 0, 'confirmed' => 0, 'pending' => 0, 'cancelled' => 0];
        
        // 查询个人预约
        if ($type === '' || $type === 'personal') {
            $personalReservations = getPersonalReservations($date, $status, $keyword);
            foreach ($personalReservations as $reservation) {
                $reservation['type'] = 'personal';
                $reservations[] = $reservation;
            }
        }
        
        // 查询团队预约
        if ($type === '' || $type === 'team') {
            $teamReservations = getTeamReservations($date, $status, $keyword);
            foreach ($teamReservations as $reservation) {
                $reservation['type'] = 'team';
                $reservations[] = $reservation;
            }
        }
        
        // 计算统计数据
        foreach ($reservations as $reservation) {
            $statistics['total']++;
            switch ($reservation['status']) {
                case 0:
                    $statistics['pending']++;
                    break;
                case 1:
                    $statistics['confirmed']++;
                    break;
                case 2:
                case 3:
                    $statistics['cancelled']++;
                    break;
            }
        }
        
        // 按创建时间排序
        usort($reservations, function($a, $b) {
            return strcmp($b['created_at'], $a['created_at']);
        });
        
        echo json_encode([
            'code' => 200,
            'message' => '获取成功',
            'data' => [
                'reservations' => $reservations,
                'statistics' => $statistics
            ]
        ]);
        
    } catch (Exception $e) {
        echo json_encode(['code' => 500, 'message' => '获取预约失败: ' . $e->getMessage()]);
    }
}

function getPersonalReservations($date, $status, $keyword) {
    $sql = "SELECT id, contact_name, contact_phone, visitor_count, visit_date, visit_time, 
                   status, special_requirements, review_note, created_at
            FROM personal_reservations 
            WHERE 1=1";
    $params = [];
    
    if ($date) {
        $sql .= " AND visit_date = ?";
        $params[] = $date;
    }
    
    if ($status !== '') {
        $sql .= " AND status = ?";
        $params[] = $status;
    }
    
    if ($keyword) {
        $sql .= " AND (contact_name LIKE ? OR contact_phone LIKE ?)";
        $params[] = "%$keyword%";
        $params[] = "%$keyword%";
    }
    
    $sql .= " ORDER BY created_at DESC";
    
    $stmt = $GLOBALS['pdo']->prepare($sql);
    $stmt->execute($params);
    
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

function getTeamReservations($date, $status, $keyword) {
    $sql = "SELECT id, team_name as contact_name, contact_phone, visitor_count, visit_date, visit_time,
                   status, purpose, special_requirements, review_note, created_at
            FROM team_reservations 
            WHERE 1=1";
    $params = [];
    
    if ($date) {
        $sql .= " AND visit_date = ?";
        $params[] = $date;
    }
    
    if ($status !== '') {
        $sql .= " AND status = ?";
        $params[] = $status;
    }
    
    if ($keyword) {
        $sql .= " AND (team_name LIKE ? OR contact_name LIKE ? OR contact_phone LIKE ?)";
        $params[] = "%$keyword%";
        $params[] = "%$keyword%";
        $params[] = "%$keyword%";
    }
    
    $sql .= " ORDER BY created_at DESC";
    
    $stmt = $GLOBALS['pdo']->prepare($sql);
    $stmt->execute($params);
    
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

function getReservationDetail() {
    $type = $_GET['type'] ?? '';
    $id = $_GET['id'] ?? 0;
    
    if (!$type || !$id) {
        echo json_encode(['code' => 400, 'message' => '参数错误']);
        return;
    }
    
    try {
        if ($type === 'personal') {
            $stmt = $GLOBALS['pdo']->prepare("
                SELECT pr.*, u.nickname, u.real_name, u.phone as user_phone
                FROM personal_reservations pr
                LEFT JOIN users u ON pr.user_id = u.id
                WHERE pr.id = ?
            ");
        } else {
            $stmt = $GLOBALS['pdo']->prepare("
                SELECT tr.*, u.nickname, u.real_name, u.phone as user_phone
                FROM team_reservations tr
                LEFT JOIN users u ON tr.user_id = u.id
                WHERE tr.id = ?
            ");
        }
        
        $stmt->execute([$id]);
        $reservation = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$reservation) {
            echo json_encode(['code' => 404, 'message' => '预约不存在']);
            return;
        }
        
        echo json_encode([
            'code' => 200,
            'message' => '获取成功',
            'data' => $reservation
        ]);
        
    } catch (Exception $e) {
        echo json_encode(['code' => 500, 'message' => '获取详情失败: ' . $e->getMessage()]);
    }
}

function reviewReservation() {
    // 检查权限
    if (!hasPermission('reservations.edit')) {
        echo json_encode(['code' => 403, 'message' => '权限不足']);
        return;
    }
    
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input || !isset($input['type'], $input['id'], $input['status'])) {
        echo json_encode(['code' => 400, 'message' => '参数错误']);
        return;
    }
    
    try {
        $table = $input['type'] === 'personal' ? 'personal_reservations' : 'team_reservations';
        
        $stmt = $GLOBALS['pdo']->prepare("
            UPDATE $table 
            SET status = ?, review_note = ?, updated_at = CURRENT_TIMESTAMP 
            WHERE id = ?
        ");
        $stmt->execute([
            $input['status'],
            $input['review_note'] ?? '',
            $input['id']
        ]);
        
        if ($stmt->rowCount() > 0) {
            echo json_encode([
                'code' => 200,
                'message' => '审核成功'
            ]);
        } else {
            echo json_encode(['code' => 404, 'message' => '预约不存在']);
        }
        
    } catch (Exception $e) {
        echo json_encode(['code' => 500, 'message' => '审核失败: ' . $e->getMessage()]);
    }
}

function exportReservations() {
    // 导出功能实现
    echo json_encode(['code' => 200, 'message' => '导出功能开发中']);
}

function hasPermission($permission) {
    // 简化权限检查，实际应该根据用户角色检查
    return true;
}
?>